import { useEffect, useRef, useState } from 'react';

interface PagePreloaderOptions {
  preloadDelay?: number; // 预加载延迟时间（毫秒）
  backgroundKeepAlive?: boolean; // 是否在后台保持页面活跃
  maxBackgroundPages?: number; // 最大后台页面数量
}

interface PageState {
  path: string;
  component: React.ComponentType<any>;
  isLoaded: boolean;
  isActive: boolean;
  lastAccessTime: number;
  data?: any;
}

class PageManager {
  private static instance: PageManager;
  private pages: Map<string, PageState> = new Map();
  private preloadQueue: string[] = [];
  private backgroundPages: string[] = [];
  private maxBackgroundPages: number = 3;

  static getInstance(): PageManager {
    if (!PageManager.instance) {
      PageManager.instance = new PageManager();
    }
    return PageManager.instance;
  }

  setMaxBackgroundPages(max: number) {
    this.maxBackgroundPages = max;
  }

  // 预加载页面
  async preloadPage(path: string, component: React.ComponentType<any>, delay: number = 0) {
    if (this.pages.has(path)) {
      return;
    }

    if (delay > 0) {
      setTimeout(() => {
        this.doPreload(path, component);
      }, delay);
    } else {
      this.doPreload(path, component);
    }
  }

  private doPreload(path: string, component: React.ComponentType<any>) {
    this.pages.set(path, {
      path,
      component,
      isLoaded: true,
      isActive: false,
      lastAccessTime: Date.now()
    });
  }

  // 激活页面
  activatePage(path: string) {
    const page = this.pages.get(path);
    if (page) {
      page.isActive = true;
      page.lastAccessTime = Date.now();
    }
  }

  // 将页面移到后台
  moveToBackground(path: string) {
    const page = this.pages.get(path);
    if (page) {
      page.isActive = false;
      page.lastAccessTime = Date.now();
      
      // 添加到后台页面列表
      if (!this.backgroundPages.includes(path)) {
        this.backgroundPages.push(path);
      }

      // 如果后台页面超过限制，移除最旧的页面
      if (this.backgroundPages.length > this.maxBackgroundPages) {
        const oldestPath = this.backgroundPages.shift();
        if (oldestPath) {
          this.pages.delete(oldestPath);
        }
      }
    }
  }

  // 获取页面组件
  getPageComponent(path: string): React.ComponentType<any> | null {
    const page = this.pages.get(path);
    return page ? page.component : null;
  }

  // 检查页面是否已预加载
  isPagePreloaded(path: string): boolean {
    return this.pages.has(path);
  }

  // 获取后台页面列表
  getBackgroundPages(): string[] {
    return [...this.backgroundPages];
  }

  // 清理所有页面
  clearAll() {
    this.pages.clear();
    this.preloadQueue = [];
    this.backgroundPages = [];
  }
}

export const usePagePreloader = (options: PagePreloaderOptions = {}) => {
  const {
    preloadDelay = 1000,
    maxBackgroundPages = 3
  } = options;

  const pageManager = useRef(PageManager.getInstance());
  const [preloadedPages, setPreloadedPages] = useState<Set<string>>(new Set());

  useEffect(() => {
    pageManager.current.setMaxBackgroundPages(maxBackgroundPages);
  }, [maxBackgroundPages]);

  // 预加载页面
  const preloadPage = async (path: string, component: React.ComponentType<any>) => {
    await pageManager.current.preloadPage(path, component, preloadDelay);
    setPreloadedPages(prev => {
      const newSet = new Set(prev);
      newSet.add(path);
      return newSet;
    });
  };

  // 激活当前页面
  const activateCurrentPage = (pathname: string) => {
    pageManager.current.activatePage(pathname);
  };

  // 将页面移到后台
  const moveToBackground = (path: string) => {
    pageManager.current.moveToBackground(path);
  };

  // 获取预加载的页面组件
  const getPreloadedComponent = (path: string) => {
    return pageManager.current.getPageComponent(path);
  };

  // 检查页面是否已预加载
  const isPreloaded = (path: string) => {
    return pageManager.current.isPagePreloaded(path);
  };

  // 获取后台页面
  const getBackgroundPages = () => {
    return pageManager.current.getBackgroundPages();
  };

  return {
    preloadPage,
    activateCurrentPage,
    moveToBackground,
    getPreloadedComponent,
    isPreloaded,
    getBackgroundPages,
    preloadedPages
  };
};

export default PageManager;
